<?php

/**
 * 转换SQL关键字
 *
 * @param unknown_type $string
 * @return unknown
 */
function strip_sql($string) {
	$pattern_arr = array(
            "/\bunion\b/i",
            "/\bselect\b/i",
            "/\bupdate\b/i",
            "/\bdelete\b/i",
            "/\boutfile\b/i",
            "/\bor\b/i",
            "/\bchar\b/i",
            "/\bconcat\b/i",
            "/\btruncate\b/i",
            "/\bdrop\b/i",            
            "/\binsert\b/i", 
            "/\brevoke\b/i", 
            "/\bgrant\b/i",      
            "/\breplace\b/i", 
            "/\balert\b/i", 
            "/\brename\b/i",            
            "/\bcreate\b/i",
            "/\bmaster\b/i",
            "/\bdeclare\b/i",
            "/\bsource\b/i",
            "/\bload\b/i",
            "/\bcall\b/i", 
            "/\bexec\b/i",            
	);
	$replace_arr = array(
            'ｕｎｉｏｎ',
            'ｓｅｌｅｃｔ',
            'ｕｐｄａｔｅ',
            'ｄｅｌｅｔｅ',
            'ｏｕｔｆｉｌｅ',
            'ｏｒ',
            'ｃｈａｒ',
            'ｃｏｎｃａｔ',
            'ｔｒｕｎｃａｔｅ',
            'ｄｒｏｐ',            
            'ｉｎｓｅｒｔ',
            'ｒｅｖｏｋｅ',
            'ｇｒａｎｔ',
            'ｒｅｐｌａｃｅ',
            'ａｌｅｒｔ',
            'ｒｅｎａｍｅ',
            'ｃｒｅａｔｅ',
            'ｍａｓｔｅｒ',
            'ｄｅｃｌａｒｅ',
            'ｓｏｕｒｃｅ',
            'ｌｏａｄ',
            'ｃａｌｌ',         
            'ｅｘｅｃ',            
	);

	return is_array($string) ? array_map('strip_sql', $string) : preg_replace($pattern_arr, $replace_arr, $string);
}

/**
 * @param $arr
 * @param $key_name
 * @return array
 * 将数据库中查出的列表以指定的 id 作为数组的键名 
 */
function convert_arr_key($arr, $key_name)
{
	$arr2 = array();
	foreach($arr as $key => $val){
		$arr2[$val[$key_name]] = $val;
	}
	return $arr2;
}

function encrypt($str){
	return md5(C("AUTH_CODE").$str);
}

function tlc_hash($password,$salt){
    $password = $salt.md5($password);
    $password = hash('sha256', $password,true);

    for ($i=0;$i<15;$i++){
        if($i == 14){
            $password = hash('sha256', $password);
        }else{
            $password = hash('sha256', $password,true);
        }
    }

    return $password;
}
/**
 * 获取数组中的某一列
 * @param type $arr 数组
 * @param type $key_name  列名
 * @return type  返回那一列的数组
 */
function get_arr_column($arr, $key_name)
{
	$arr2 = array();
	if(!empty($arr)){
		foreach($arr as $key => $val){
			$arr2[] = $val[$key_name];
		}
	}
	return $arr2;
}


/**
 * 获取url 中的各个参数  类似于 pay_code=alipay&bank_code=ICBC-DEBIT
 * @param type $str
 * @return type
 */
function parse_url_param($str){
    $data = array();
    $parameter = explode('&',end(explode('?',$str)));
    foreach($parameter as $val){
        $tmp = explode('=',$val);
        $data[$tmp[0]] = $tmp[1];
    }
    return $data;
}


/**
 * 二维数组排序
 * @param $arr
 * @param $keys
 * @param string $type
 * @return array
 */
function array_sort($arr, $keys, $type = 'desc')
{
    $key_value = $new_array = array();
    foreach ($arr as $k => $v) {
        $key_value[$k] = $v[$keys];
    }
    if ($type == 'asc') {
        asort($key_value);
    } else {
        arsort($key_value);
    }
    reset($key_value);
    foreach ($key_value as $k => $v) {
        $new_array[$k] = $arr[$k];
    }
    return $new_array;
}


/**
 * 多维数组转化为一维数组
 * @param 多维数组
 * @return array 一维数组
 */
function array_multi2single($array)
{
    static $result_array = array();
    foreach ($array as $value) {
        if (is_array($value)) {
            array_multi2single($value);
        } else
            $result_array [] = $value;
    }
    return $result_array;
}

/**
 * 友好时间显示
 * @param $time
 * @return bool|string
 */
function friend_date($time)
{
    if (!$time)
        return false;
    $fdate = '';
    $d = time() - intval($time);
    $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //得出年
    $md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //得出月
    $byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
    $yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
    $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
    $td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
    $atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
    if ($d == 0) {
        $fdate = '刚刚';
    } else {
        switch ($d) {
            case $d < $atd:
                $fdate = date('Y年m月d日', $time);
                break;
            case $d < $td:
                $fdate = '后天' . date('H:i', $time);
                break;
            case $d < 0:
                $fdate = '明天' . date('H:i', $time);
                break;
            case $d < 60:
                $fdate = $d . '秒前';
                break;
            case $d < 3600:
                $fdate = floor($d / 60) . '分钟前';
                break;
            case $d < $dd:
                $fdate = floor($d / 3600) . '小时前';
                break;
            case $d < $yd:
                $fdate = '昨天' . date('H:i', $time);
                break;
            case $d < $byd:
                $fdate = '前天' . date('H:i', $time);
                break;
            case $d < $md:
                $fdate = date('m月d日 H:i', $time);
                break;
            case $d < $ld:
                $fdate = date('m月d日', $time);
                break;
            default:
                $fdate = date('Y年m月d日', $time);
                break;
        }
    }
    return $fdate;
}


/**
 * 返回状态和信息
 * @param $status
 * @param $info
 * @return array
 */
function arrayRes($status, $info, $url = "")
{
    return array("status" => $status, "info" => $info, "url" => $url);
}
       
/**
 * @param $arr
 * @param $key_name
  * @param $key_name2
 * @return array
 * 将数据库中查出的列表以指定的 id 作为数组的键名 数组指定列为元素 的一个数组
 */
function get_id_val($arr, $key_name,$key_name2)
{
	$arr2 = array();
	foreach($arr as $key => $val){
		$arr2[$val[$key_name]] = $val[$key_name2];
	}
	return $arr2;
}

/**
 *  自定义函数 判断 用户选择 从下面的列表中选择 可选值列表：不能为空
 * @param type $attr_values
 * @return boolean
 */
function checkAttrValues($attr_values)
{        
    if((trim($attr_values) == '') && ($_POST['attr_input_type'] == '1'))        
        return false;
    else
        return true;
 }
 
 // 定义一个函数getIP() 客户端IP，
function getIP(){            
    if (getenv("HTTP_CLIENT_IP"))
         $ip = getenv("HTTP_CLIENT_IP");
    else if(getenv("HTTP_X_FORWARDED_FOR"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if(getenv("REMOTE_ADDR"))
         $ip = getenv("REMOTE_ADDR");
    else $ip = "Unknow";
    
    if(preg_match('/^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1 -9]?\d))))$/', $ip))          
        return $ip;
    else
        return '';
}
// 服务器端IP
 function serverIP(){   
  return gethostbyname($_SERVER["SERVER_NAME"]);   
 }  
 
 
 /**
  * 自定义函数递归的复制带有多级子目录的目录
  * 递归复制文件夹
  * @param type $src 原目录
  * @param type $dst 复制到的目录
  */                        
//参数说明：            
//自定义函数递归的复制带有多级子目录的目录
function recurse_copy($src, $dst)
{
	$now = time();
	$dir = opendir($src);
	@mkdir($dst);
	while (false !== $file = readdir($dir)) {
		if (($file != '.') && ($file != '..')) {
			if (is_dir($src . '/' . $file)) {
				recurse_copy($src . '/' . $file, $dst . '/' . $file);
			}
			else {
				if (file_exists($dst . DIRECTORY_SEPARATOR . $file)) {
					if (!is_writeable($dst . DIRECTORY_SEPARATOR . $file)) {
						exit($dst . DIRECTORY_SEPARATOR . $file . '不可写');
					}
					@unlink($dst . DIRECTORY_SEPARATOR . $file);
				}
				if (file_exists($dst . DIRECTORY_SEPARATOR . $file)) {
					@unlink($dst . DIRECTORY_SEPARATOR . $file);
				}
				$copyrt = copy($src . DIRECTORY_SEPARATOR . $file, $dst . DIRECTORY_SEPARATOR . $file);
				if (!$copyrt) {
					echo 'copy ' . $dst . DIRECTORY_SEPARATOR . $file . ' failed<br>';
				}
			}
		}
	}
	closedir($dir);
}

// 递归删除文件夹
function delFile($dir,$file_type='') {
	if(is_dir($dir)){
		$files = scandir($dir);
		//打开目录 //列出目录中的所有文件并去掉 . 和 ..
		foreach($files as $filename){
			if($filename!='.' && $filename!='..'){
				if(!is_dir($dir.'/'.$filename)){
					if(empty($file_type)){
						unlink($dir.'/'.$filename);
					}else{
						if(is_array($file_type)){
							//正则匹配指定文件
							if(preg_match($file_type[0],$filename)){
								unlink($dir.'/'.$filename);
							}
						}else{
							//指定包含某些字符串的文件
							if(false!=stristr($filename,$file_type)){
								unlink($dir.'/'.$filename);
							}
						}
					}
				}else{
					delFile($dir.'/'.$filename);
					rmdir($dir.'/'.$filename);
				}
			}
		}
	}else{
		if(file_exists($dir)) unlink($dir);
	}
}

 
/**
 * 多个数组的笛卡尔积
*
* @param unknown_type $data
*/
function combineDika() {
	$data = func_get_args();
	$data = current($data);
	$cnt = count($data);
	$result = array();
    $arr1 = array_shift($data);
	foreach($arr1 as $key=>$item) 
	{
		$result[] = array($item);
	}		

	foreach($data as $key=>$item) 
	{                                
		$result = combineArray($result,$item);
	}
	return $result;
}


/**
 * 两个数组的笛卡尔积
 * @param unknown_type $arr1
 * @param unknown_type $arr2
*/
function combineArray($arr1,$arr2) {		 
	$result = array();
	foreach ($arr1 as $item1) 
	{
		foreach ($arr2 as $item2) 
		{
			$temp = $item1;
			$temp[] = $item2;
			$result[] = $temp;
		}
	}
	return $result;
}
/**
 * 将二维数组以元素的某个值作为键 并归类数组
 * array( array('name'=>'aa','type'=>'pay'), array('name'=>'cc','type'=>'pay') )
 * array('pay'=>array( array('name'=>'aa','type'=>'pay') , array('name'=>'cc','type'=>'pay') ))
 * @param $arr 数组
 * @param $key 分组值的key
 * @return array
 */
function group_same_key($arr,$key){
    $new_arr = array();
    foreach($arr as $k=>$v ){
        $new_arr[$v[$key]][] = $v;
    }
    return $new_arr;
}

/**
 * 获取随机字符串
 * @param int $randLength  长度
 * @param int $addtime  是否加入当前时间戳
 * @param int $includenumber   是否包含数字
 * @return string
 */
function get_rand_str($randLength=6,$addtime=1,$includenumber=0){
    if ($includenumber){
        $chars='abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
    }else {
        $chars='abcdefghijklmnopqrstuvwxyz';
    }
    $len=strlen($chars);
    $randStr='';
    for ($i=0;$i<$randLength;$i++){
        $randStr.=$chars[rand(0,$len-1)];
    }
    $tokenvalue=$randStr;
    if ($addtime){
        $tokenvalue=$randStr.time();
    }
    return $tokenvalue;
}

/**
 * CURL请求
 * @param $url 请求url地址
 * @param $method 请求方法 get post
 * @param null $postfields post数据数组
 * @param array $headers 请求header信息
 * @param bool|false $debug  调试开启 默认false
 * @return mixed
 */
function httpRequest($url, $method, $postfields = null, $headers = array(), $debug = false) {
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if($ssl){
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        echo "=====post data======\r\n";
        var_dump($postfields);
        echo "=====info===== \r\n";
        print_r($requestinfo);
        echo "=====response=====\r\n";
        print_r($response);
    }
    curl_close($ci);
    return $response;
	//return array($http_code, $response,$requestinfo);
}

/**
 * 过滤数组元素前后空格 (支持多维数组)
 * @param $array 要过滤的数组
 * @return array|string
 */
function trim_array_element($array){
    if(!is_array($array))
        return trim($array);
    return array_map('trim_array_element',$array);
}

/**
 * 检查手机号码格式
 * @param $mobile 手机号码
 */
function check_mobile($mobile){
    $pattern = '/^1[3-9]\d{9}$/';
    // $pattern = '/1[3456789]\d{9}$/';
    if(preg_match($pattern,$mobile))
        return true;
    return false;
}

/**
 * 检查邮箱地址格式
 * @param $email 邮箱地址
 */
function check_email($email){
    if(filter_var($email,FILTER_VALIDATE_EMAIL))
        return true;
    return false;
}


/**
 *   实现中文字串截取无乱码的方法
 */
function getSubstr($string, $start, $length) {
      if(mb_strlen($string,'utf-8')>$length){
          $str = mb_substr($string, $start, $length,'utf-8');
          return $str.'...';
      }else{
          return $string;
      }
}


/**
 * 判断当前访问的用户是  PC端  还是 手机端  返回true 为手机端  false 为PC 端
 * @return boolean
 */
/**
　　* 是否移动端访问访问
　　*
　　* @return bool
　　*/
function isMobile()
{
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
    return true;

    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
    {
    // 找不到为flase,否则为true
    return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT']))
    {
        $clientkeywords = array ('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile');
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
            return true;
    }
        // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT']))
    {
    // 如果只支持wml并且不支持html那一定是移动设备
    // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
        {
            return true;
        }
    }
            return false;
 } 

//php获取中文字符拼音首字母
function getFirstCharter($str){
      if(empty($str))
      {
            return ''; 
      }
      $fchar=ord($str{0});
      if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
      $s1=iconv('UTF-8','gb2312',$str);
      $s2=iconv('gb2312','UTF-8',$s1);
      $s=$s2==$str?$s1:$str;
      $asc=ord($s{0})*256+ord($s{1})-65536;
     if($asc>=-20319&&$asc<=-20284) return 'A';
     if($asc>=-20283&&$asc<=-19776) return 'B';
     if($asc>=-19775&&$asc<=-19219) return 'C';
     if($asc>=-19218&&$asc<=-18711) return 'D';
     if($asc>=-18710&&$asc<=-18527) return 'E';
     if($asc>=-18526&&$asc<=-18240) return 'F';
     if($asc>=-18239&&$asc<=-17923) return 'G';
     if($asc>=-17922&&$asc<=-17418) return 'H';
     if($asc>=-17417&&$asc<=-16475) return 'J';
     if($asc>=-16474&&$asc<=-16213) return 'K';
     if($asc>=-16212&&$asc<=-15641) return 'L';
     if($asc>=-15640&&$asc<=-15166) return 'M';
     if($asc>=-15165&&$asc<=-14923) return 'N';
     if($asc>=-14922&&$asc<=-14915) return 'O';
     if($asc>=-14914&&$asc<=-14631) return 'P';
     if($asc>=-14630&&$asc<=-14150) return 'Q';
     if($asc>=-14149&&$asc<=-14091) return 'R';
     if($asc>=-14090&&$asc<=-13319) return 'S';
     if($asc>=-13318&&$asc<=-12839) return 'T';
     if($asc>=-12838&&$asc<=-12557) return 'W';
     if($asc>=-12556&&$asc<=-11848) return 'X';
     if($asc>=-11847&&$asc<=-11056) return 'Y';
     if($asc>=-11055&&$asc<=-10247) return 'Z';
     return null;
}

/**
 * 	作用：array转xml
 */
function arrayToXml($arr)
{
    $xml = "<xml>";
    foreach ($arr as $key=>$val)
    {
        if (is_numeric($val))
        {
            $xml.="<".$key.">".$val."</".$key.">";

        }
        else
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
    }
    $xml.="</xml>";
    return $xml;
}

//@add by wangqh 修复返回列表默认翻到第一页问题 @{
function checkIsBack(){
      session("is_back" ,  I('is_back',0));
     
}
 
function cacheIsBack(){
    session("is_back" , 1);
}

function delIsBack(){
    session("is_back" , 0);
}

function cachePage($p){
   session("TPSHOP_PAGE" , $p);
}

function getPageFromCache(){
    return session("TPSHOP_PAGE");
}

function juti_quyu($id){
	if($id){
    $fenlei=M('region a')
    ->field('a.id,a.name,a.level,
    b.id idb,b.name nameb,
    c.id idc,c.parent_id parent_idc,c.name namec
    ')
    ->join('ty_region b on a.parent_id=b.id','LEFT')
    ->join('ty_region c on b.parent_id=c.id','LEFT')
    ->where('a.id='.$id)->find();
	
    	if($fenlei['level']==4){
    		$top1=M('region')->where('id='.$fenlei['parent_idc'])->find();
    		$strs= $top1['name'].' > '.$fenlei['namec'].' > '.$fenlei['nameb'].' > '.$fenlei['name'];
    	}elseif($fenlei['level']==3){
    		$strs= $fenlei['namec'].' > '.$fenlei['nameb'].' > '.$fenlei['name'];
    	}elseif($fenlei['level']==2){
    		$strs= $fenlei['nameb'].' > '.$fenlei['name'];
    	}else{
    		$strs= $fenlei['name'];
    	}
	return $strs;
	}
}

function huodong_name($prom_type,$zhekou=0){
    switch($prom_type)
    {
        case 0:
            // $str = str_replace("0","",$zhekou).'折秒杀！';
            $str =($zhekou/10).'折秒杀！';
            break;
        case 1:
            $str = '降价'.$zhekou.'元促销！';
            break;
        case 4:
            $zhekou = explode('/',$zhekou);
            $str = '卖M送N：'.$zhekou[0].'送'.$zhekou[1];
            break;
        case 5:
            // $str = str_replace("0","",$zhekou).'折秒杀！';
            $str =($zhekou/10).'折秒杀！';
            break;
        default:
            $str=$zhekou.'元一口价！';
    }
    return $str;
}

function quyu_price($quyu_user,$store_id,$goods_id = 0){
    $quyu_hl=100;
    $store_quyu=M('store')->where("store_id=".$store_id)->getField('quyu_price');
    $quyu = M('goods')->where(['goods_id'=>$goods_id])->getField('quyu_yijia');
    if(!empty($quyu) && $quyu!='[]' && !empty($quyu_user)){
        foreach(json_decode($quyu,true) as $v){
            if($quyu_user==$v['id']){
                $quyu_hl=(int)$v['hl'];
                break;
            }
        }
    }
    if($quyu_hl == 100){ //先看看产品有没有区域价格，没有再查店铺，最后没有返回100
        if(!empty($store_quyu) && $store_quyu!='[]' && !empty($quyu_user)){
            foreach(json_decode($store_quyu,true) as $v){
                if($quyu_user==$v['id']){
                    $quyu_hl=(int)$v['hl'];
                    break;
                }
            }
        }
    }
    return $quyu_hl/100;
}


/**
 * 首页接口使用的
 */
function quyu_price_index_home($quyu_user,$store_quyu,$quyu){
    $quyu_hl=100;
//    $store_quyu=M('store')->where("store_id=".$store_id)->getField('quyu_price');
//    $quyu = M('goods')->where(['goods_id'=>$goods_id])->getField('quyu_yijia');
    if(!empty($quyu) && $quyu!='[]' && !empty($quyu_user)){
        foreach(json_decode($quyu,true) as $v){
            if($quyu_user==$v['id']){
                $quyu_hl=(int)$v['hl'];
                break;
            }
        }
    }
    if($quyu_hl == 100){ //先看看产品有没有区域价格，没有再查店铺，最后没有返回100
        if(!empty($store_quyu) && $store_quyu!='[]' && !empty($quyu_user)){
            foreach(json_decode($store_quyu,true) as $v){
                if($quyu_user==$v['id']){
                    $quyu_hl=(int)$v['hl'];
                    break;
                }
            }
        }
    }
    return $quyu_hl/100;
}


/**
 * 生成h5和App的订单二维码(直接扫码后跳转惠市宝接口下单并付款)
 * @param $order
 * @param string $self
 * @param int $echo
 * @return string
 */
function tuihuoQRcode($order,$self='self',$echo=0){
    // echo json_encode($order);exit;
    Vendor('phpqrcode.phpqrcode');
    $object = new \QRcode();
    if($order && $order['id']){
        $mydata = json_encode(['id'=>$order['id'],'type'=>'tuihuo']);
        // $picname=\md5($mydata);
        $level = 'L'; //容错级别 分为L、M、Q、H
        $size = 10; //点的大小 1~10,手机端用4即可
        $filename = '/Public/tuihuoqrcode/'.$self.'_'.$order['id'].'.png';
        if (!file_exists($filename)) {
            $object->png($mydata,'.'.$filename,$level,$size,0);
        }
    }

    if($echo == 1){
        $img = file_get_contents(SITE_URL.$filename);
        $img = $img ?: file_get_contents('http://'.$_SERVER['HTTP_HOST'].$filename);
        $data = base64_encode($img);
        return 'data:image/png;base64,'.$data;
    }

    if($echo == 2){
        return '/Public/tuihuoqrcode/'.$self.'_'.$order['id'].'.png';
    }
}


/**
 * 两个时间对比相差多少个小时
 * @param $timestamp1
 * @param $timestamp2
 * @return float|int
 */
function calculateHourDiff($timestamp1, $timestamp2) {
    $diffSeconds = abs($timestamp2 - $timestamp1);  // 计算两个时间戳的差值（以秒为单位）
    return round(($diffSeconds / 3600),2);  // 将差值转换为小时
}


/**
 * 获取直播
 * @param $store_id
 * @return false
 */
function getWechatLive()
{
    vendor('grafika.autoloader');
    $paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();

    $config_value = unserialize($paymentPlugin['config_value']);
    $APPID=$config_value['appid'];
    $SECRET = $config_value['appsecret'];

    $api = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$APPID}&secret={$SECRET}";
    $res = curl_get($api);
    $res = json_decode($res, true);

    if (empty($res['access_token'])) {
        return false;
    }

    $accessToken = $res['access_token'];

    $api = "https://api.weixin.qq.com/wxa/business/getliveinfo?access_token={$accessToken}";
    $curl = new \Grafika\Curl();
    $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
    $parm['start'] = 0;
    $parm['limit'] = 1000;
    $curl->post($api, json_encode($parm));
    $lives = json_decode($curl->response, true);

    if ($lives && $lives['room_info']) {
        foreach ($lives['room_info'] as $live) {
            $data = [];
            if ($live['goods']) {
                $live['goods'] = json_encode($live['goods']);
            }
            $liveInfo = M('live')->where(['roomid' => $live['roomid']])->find();

            if ($liveInfo) {
                $data['name'] = $live['name'];
                $data['live_status'] = $live['live_status'];
                $data['start_time'] = $live['start_time'];
                $data['anchor_name'] = $live['anchor_name'];
                $data['goods'] = $live['goods'];
                $data['share_img'] = $live['share_img'];
                $data['live_type'] = $live['live_type'];
                M('live')->where(['roomid' => $live['roomid']])->save($data);
            } else {
                $data['roomid'] = $live['roomid'];
                $data['name'] = $live['name'];
                $data['live_status'] = $live['live_status'];
                $data['start_time'] = $live['start_time'];
                $data['anchor_name'] = $live['anchor_name'];
                $data['goods'] = $live['goods'];
                $data['share_img'] = $live['share_img'];
                $data['live_type'] = $live['live_type'];
                M('live')->add($data);
                // $this->allowField(true)->save($live);
            }
        }
    }
}

function curl_get($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    $json_data = curl_exec($ch);
    curl_close($ch);
    return  $json_data;
}


/**
 * CURL GET || post请求
 * @desc: GET与post都通用
 * @param: $url 请求的地址
 *       $isPostRequest 默认true是GET请求，否则是POST请求
 *       $data array  请求的参数
 *       $certParam  array  ['cert_path']    ['key_path']
 * @return:
 */
function curl_http($url, $isPostRequest=false, $data=[], $header=[], $certParam=[]){ // 模拟提交数据函数
    $curlObj = curl_init(); // 启动一个CURL会话
    //如果是POST请求
    if( $isPostRequest ){
        curl_setopt($curlObj, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curlObj, CURLOPT_POSTFIELDS, http_build_query($data)); // Post提交的数据包
    }else{  //get请求检查是否拼接了参数，如果没有，检查$data是否有参数，有参数就进行拼接操作
        $getParamStr = '';
        if(!empty($data) && is_array($data)){
            $tmpArr = [];
            foreach ($data as $k=>$v){
                $tmpArr[] = $k . '=' . $v;
            }
            $getParamStr = implode('&', $tmpArr);
        }
        //检查链接中是否有参数
        $url .= strpos($url, '?') !== false ? '&' . $getParamStr : '?' . $getParamStr;
    }
    curl_setopt($curlObj, CURLOPT_URL, $url); // 要访问的地址
    //检查链接是否https请求
    if(strpos($url, 'https') !== false){
        //设置证书
        if( !empty($certParam) && isset($certParam['cert_path']) && isset($certParam['key_path']) ){
            curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
            curl_setopt($curlObj, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
            //设置证书
            //使用证书：cert 与 key 分别属于两个.pem文件
            curl_setopt($curlObj, CURLOPT_SSLCERTTYPE,'PEM');
            curl_setopt($curlObj, CURLOPT_SSLCERT, $certParam['cert_path']);
            curl_setopt($curlObj, CURLOPT_SSLKEYTYPE,'PEM');
            curl_setopt($curlObj, CURLOPT_SSLKEY, $certParam['key_path']);
        }else{
            curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
            curl_setopt($curlObj, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        }
    }
    // 模拟用户使用的浏览器
    if(isset($_SERVER['HTTP_USER_AGENT'])){
        curl_setopt($curlObj, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    }
    curl_setopt($curlObj, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curlObj, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($curlObj, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curlObj, CURLOPT_HTTPHEADER, $header);   //设置头部
    curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $result = curl_exec($curlObj); // 执行操作
    if ( curl_errno($curlObj) ) {
        $result = 'error: '.curl_error($curlObj);//捕抓异常
    }
    curl_close($curlObj); // 关闭CURL会话
    return $result; // 返回数据，json格式
}

function is_intval($str){
    if (is_numeric($str) && strpos($str, '.') !== false) {
        //包含小数点
        $substring = "0".substr($str, 1, strlen($str) - 1);
        if($substring > 0.000){
        }else{
            return intval($str);
        }
        $substring = substr($str, 4, 1);
        if($substring == 0){
            return substr($str, 0, -1);
        }
        return $str;
    } else {
        //不包含小数点
        return intval($str);
    }
}
